package com.yexiao.cofe.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yexiao.cofe.business.mapper.*;
import com.yexiao.cofe.business.pojo.*;
import com.yexiao.cofe.business.service.ParamTemplateService;
import com.yexiao.cofe.common.exception.BusinessException;
import com.yexiao.core.util.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author lkl
 * @since 2025/3/31
 */
@Service
public class ParamTemplateServiceImpl implements ParamTemplateService {

    @Resource
    private ParamTemplateMapper templateMapper;
    @Resource
    private TemplateParamMapper templateParamMapper;
    @Resource
    private ParamValueMapper paramValueMapper;
    @Resource
    private ParamItemMapper paramItemMapper;
    @Autowired
    private StoreMapper storeMapper;

    @Override
    public void addTemplate(JSONObject param) {
        String storeId = JSONUtil.checkAndGetStr(param, "storeId");
        String name = JSONUtil.checkAndGetStr(param, "name");
        String description = JSONUtil.checkAndGetStr(param, "description");

        Store store = storeMapper.selectByStoreId(storeId);
        if(store == null) {
            throw new BusinessException("门店不存在");
        }

        ParamTemplate template = templateMapper.selectParamTemplateByStoreIdAndName(storeId, name);
        if(template != null) {
            throw new BusinessException("模板名重复");
        }

        ParamTemplate newTemplate = new ParamTemplate(storeId, name, description);
        templateMapper.insert(newTemplate);
    }

    @Override
    public void modifyTemplate(JSONObject param) {
        Integer id = JSONUtil.checkAndGetInt(param, "id");
        String name = JSONUtil.getStr(param, "name");
        String description = JSONUtil.getStr(param, "description");

        templateMapper.modifyTemplate(id, name, description);
    }

    @Override
    public void delTemplate(Integer templateId) {
        if(templateId == null) {
            throw new BusinessException("参数缺失");
        }
        templateMapper.deleteById(templateId);
    }

    @Override
    @Transient
    public void bindParamValue(JSONObject param) {
        Integer templateId = JSONUtil.checkAndGetInt(param, "templateId");
        List<Integer> paramValueIdList = JSONUtil.getList(param, Integer.class, "paramValueIdList");

        ParamTemplate paramTemplate = templateMapper.selectById(templateId);
        if(paramTemplate == null) {
            throw new BusinessException("参数模板不存在");
        }
        templateParamMapper.deleteByTemplateId(templateId);

        if(CollectionUtil.isNotEmpty(paramValueIdList)) {
            List<ParamValue> paramValueList = paramValueMapper.selectBatchIds(paramValueIdList);
            List<TemplateParam> list = new ArrayList<>();
            for(ParamValue paramValue : paramValueList) {
                TemplateParam templateParam = new TemplateParam(templateId, paramValue.getParamItemId(), paramValue.getId(), paramValue.getValue());
                list.add(templateParam);
            }

            templateParamMapper.insert(list);
        } else {
            throw new BusinessException("参数值不存在");
        }
    }

    @Override
    public JSONObject getTemplateDetail(Integer templateId) {
        if(templateId == null) {
            throw new BusinessException("参数缺失");
        }
        ParamTemplate paramTemplate = templateMapper.selectById(templateId);
        if(paramTemplate == null) {
            throw new BusinessException("模板不存在");
        }

        JSONObject res = ParamTemplate.getBaseMsg(paramTemplate);

        // 获取模板参数数据
        List<ParamItem> paramItemList = paramItemMapper.listAll();
        List<ParamValue> paramValueList = paramValueMapper.listAll();
        List<TemplateParam> templateParam = templateParamMapper.selectByTemplateId(templateId);
        Set<Integer> excludeValueIdSet = templateParam.stream().map(TemplateParam::getParamValueId).collect(Collectors.toSet());

        List<JSONObject> bindDetail = new ArrayList<>();
        for (ParamItem paramItem : paramItemList) {
            int itemId = paramItem.getId();
            JSONObject item = ParamItem.getParamItemBaseMsg(paramItem);
            List<JSONObject> haveBindValueList = new ArrayList<>();
            List<JSONObject> canBindValueList = new ArrayList<>();

            for (ParamValue paramValue : paramValueList) {
                // 不属于当前参数项
                if(paramValue.getParamItemId() != itemId) {
                    continue;
                }

                if(excludeValueIdSet.contains(paramValue.getId())) {
                    // 绑定过
                    haveBindValueList.add(ParamValue.getBaseMsg(paramValue));
                } else {
                    // 未绑定
                    canBindValueList.add(ParamValue.getBaseMsg(paramValue));
                }
            }

            item.put("canBindValueList", canBindValueList);
            item.put("haveBindValueList", haveBindValueList);
            bindDetail.add(item);
        }
        res.put("bindDetail", bindDetail);

        return res;
    }

    @Override
    public JSONObject getStoreTemplate(JSONObject param) {
        String storeId = JSONUtil.getStr(param, "storeId");
        String name = JSONUtil.getStr(param, "name");
        Integer pageNum = JSONUtil.checkAndGetInt(param, "pageNum");
        Integer pageSize = JSONUtil.checkAndGetInt(param, "pageSize");

        // 分页
        PageHelper.startPage(pageNum, pageSize);
        List<ParamTemplate> templateList = templateMapper.listByStoreId(storeId, name);
        PageInfo<ParamTemplate> pageInfo = new PageInfo<>(templateList);

        List<JSONObject> tempateResList = new ArrayList<>();
        for (ParamTemplate paramTemplate : templateList) {
            tempateResList.add(ParamTemplate.getBaseMsg(paramTemplate));
        }

        return JSONUtil.of(
                "total", pageInfo.getTotal(),
                "pageSize", pageInfo.getSize(),
                "pageNum", pageInfo.getPageNum(),
                "list", tempateResList
        );
    }

}
